// 模拟炒股账户管理云函数
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-8g3kxnyv58f85f9b'
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { action, ...params } = event

  try {
    switch (action) {
      case 'initialize':
        return await initializeAccount(wxContext.OPENID)
      case 'getAccount':
        return await getAccount(wxContext.OPENID)
      case 'updateAccount':
        return await updateAccount(wxContext.OPENID, params)
      default:
        return {
          success: false,
          error: 'invalid_action',
          message: '无效的操作类型'
        }
    }
  } catch (error) {
    console.error('模拟账户云函数执行失败:', error)
    return {
      success: false,
      error: 'function_failed',
      message: '操作失败，请重试',
      details: error.message
    }
  }
}

// 初始化账户
async function initializeAccount(openid) {
  try {
    console.log('初始化账户，openid:', openid)

    // 检查是否已有账户 - 先按_openid查询
    let existingAccount = await db.collection('simulation_accounts').where({
      _openid: openid
    }).get()

    console.log('按_openid查询结果:', existingAccount)

    // 如果按_openid查询不到，尝试按openid字段查询
    if (existingAccount.data.length === 0) {
      existingAccount = await db.collection('simulation_accounts').where({
        openid: openid
      }).get()

      console.log('按openid字段查询结果:', existingAccount)
    }

    if (existingAccount.data.length > 0) {
      // 账户已存在，返回现有账户信息
      const account = existingAccount.data[0]
      return {
        success: true,
        account: {
          totalAssets: account.totalAssets,
          availableCash: account.availableCash,
          frozenCash: account.frozenCash || 0,
          marketValue: account.marketValue,
          totalProfit: account.totalProfit,
          profitRate: account.profitRate
        },
        message: '账户已存在'
      }
    } else {
      // 创建新账户 - 同时存储_openid和openid字段
      const initialCash = 1000000 // 初始资金100万

      const result = await db.collection('simulation_accounts').add({
        data: {
          openid: openid,  // 添加openid字段
          totalAssets: initialCash,
          availableCash: initialCash,
          frozenCash: 0,
          marketValue: 0,
          totalProfit: 0,
          profitRate: 0,
          createTime: db.serverDate(),
          updateTime: db.serverDate()
        }
      })

      console.log('新账户创建成功:', result)

      return {
        success: true,
        account: {
          totalAssets: initialCash,
          availableCash: initialCash,
          frozenCash: 0,
          marketValue: 0,
          totalProfit: 0,
          profitRate: 0
        },
        message: '账户创建成功',
        accountId: result._id
      }
    }
  } catch (error) {
    console.error('初始化账户失败:', error)
    throw error
  }
}

// 获取账户信息
async function getAccount(openid) {
  try {
    // 先按_openid查询
    let result = await db.collection('simulation_accounts').where({
      _openid: openid
    }).get()

    // 如果按_openid查询不到，尝试按openid字段查询
    if (result.data.length === 0) {
      result = await db.collection('simulation_accounts').where({
        openid: openid
      }).get()
    }

    if (result.data.length > 0) {
      const account = result.data[0]
      return {
        success: true,
        account: {
          totalAssets: account.totalAssets,
          availableCash: account.availableCash,
          frozenCash: account.frozenCash || 0,
          marketValue: account.marketValue,
          totalProfit: account.totalProfit,
          profitRate: account.profitRate
        }
      }
    } else {
      return {
        success: false,
        error: 'account_not_found',
        message: '账户不存在'
      }
    }
  } catch (error) {
    console.error('获取账户信息失败:', error)
    throw error
  }
}

// 更新账户信息
async function updateAccount(openid, updateData) {
  try {
    // 先按_openid更新
    let result = await db.collection('simulation_accounts').where({
      _openid: openid
    }).update({
      data: {
        ...updateData,
        updateTime: db.serverDate()
      }
    })

    // 如果按_openid更新失败，尝试按openid更新
    if (result.stats.updated === 0) {
      result = await db.collection('simulation_accounts').where({
        openid: openid
      }).update({
        data: {
          ...updateData,
          updateTime: db.serverDate()
        }
      })
    }

    if (result.stats.updated > 0) {
      return {
        success: true,
        message: '账户更新成功'
      }
    } else {
      return {
        success: false,
        error: 'account_not_found',
        message: '账户不存在'
      }
    }
  } catch (error) {
    console.error('更新账户信息失败:', error)
    throw error
  }
}
